// maindlg.cpp : implementation of the CMainDlg class
//
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "resource.h"

#include "aboutdlg.h"
#include "maindlg.h"
#include "UIHelper.h"
#include "MediaListDlg.h"

#include "constdef.h"
#include "FileTools.h"

void GetModulePath(TCHAR* path)
{
	TCHAR*		lpTmp;
	GetModuleFileName(NULL, path, MAX_PATH);
	lpTmp = _tcsrchr(path, '\\');
	if (_tcslen(lpTmp) > 3) 
	{
		*lpTmp = _T('\0');
	}
	_tcscat(path, _T("\\"));
}


BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
	return CWindow::IsDialogMessage(pMsg);
}

BOOL CMainDlg::OnIdle()
{
	return FALSE;
}

LRESULT CMainDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	m_bLogined = false;
	m_ContoSrv = NULL;
	m_Config = NULL;

	if(!IsDirExist(U_TEMPFILEDIR))
	{
		wmkdir(U_TEMPFILEDIR);
	}

	HWND hwndMB = AtlCreateMenuBar(m_hWnd, IDR_MAINMENU,SHCMBF_HMENU);
	int a = GetLastError();
	HMENU hMenuTop = SHGetMenu(hwndMB);
	if ( !hMenuTop )
	{
		m_hMenu = GetMenu5(hwndMB, 1);
	}
	else
	{
		m_hMenu = ::GetSubMenu(hMenuTop, 1);
	}


	// center the dialog on the screen
	CenterWindow();

	DlgResize_Init(false);
	SHInitMaxDialog(m_hWnd);

	// set icons
	HICON hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
		IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
	SetIcon(hIcon, TRUE);
	HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
		IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
	SetIcon(hIconSmall, FALSE);

	// register object for message filtering and idle updates
	CMessageLoop* pLoop = _Module.GetMessageLoop();
	ATLASSERT(pLoop != NULL);
	pLoop->AddMessageFilter(this);
	pLoop->AddIdleHandler(this);

	UIAddChildWindowContainer(m_hWnd);


	m_idcList.SubclassWindow(GetDlgItem(IDC_LIST_USER));
	m_idcList.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);


	m_imgList.Create(16, 16, ILC_COLOR, 4, 8);
	HBITMAP hBMP = LoadBitmap(_Module.GetResourceInstance() ,MAKEINTRESOURCE(IDB_BITMAP_USER));
	m_imgList.Add(hBMP);
	m_imgList.Add(NULL);
	m_idcList.SetImageList(m_imgList, LVSIL_SMALL);


	//Init list control
	RECT rcList;
	m_idcList.GetClientRect(&rcList); 

	CString strCol;
	strCol.LoadString(IDS_USER);
	m_idcList.InsertColumn(0, strCol, LVCFMT_LEFT, rcList.right - rcList.left);


	//Load config
	m_Config = new CConfig();
	TCHAR path[256];
	GetModulePath(path);
	_tcscat(path, U_CONFIGNAME);
	char szIni[256];
	sprintf(szIni,"%S",path);
	m_Config->LoadConfig(szIni);

	m_ContoSrv = new CContosrv(m_Config);


	wchar_t		szW[32] = {0};
	swprintf(szW,L"%S", m_Config->m_UserInfo.userName);
	SetDlgItemText(IDC_NAME, szW);
	swprintf(szW,L"%S", m_Config->m_UserInfo.userPsw);
	SetDlgItemText(IDC_PSW, szW);
	

	SetForegroundWindow(m_hWnd);
	return TRUE;
}

LRESULT CMainDlg::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	CAboutDlg dlg;
	dlg.DoModal();
	return 0;
}

LRESULT CMainDlg::OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	// TODO: Add validation code 
	CloseDialog(wID);
	return 0;
}

LRESULT CMainDlg::OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	CloseDialog(wID);
	return 0;
}

void CMainDlg::CloseDialog(int nVal)
{
	if(m_Config)
	{
		//Save config
		TCHAR path[256];
		GetModulePath(path);
		_tcscat(path, U_CONFIGNAME);
		char szIni[256];
		sprintf(szIni,"%S",path);
		m_Config->SaveConfig(szIni);

		delete m_Config;
	}
	
	if(m_ContoSrv)
	{
		delete m_ContoSrv;
	}


	DestroyWindow();
	::PostQuitMessage(nVal);
}

LRESULT CMainDlg::OnItemChanged(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
	//UpdateMenu();
	int nIndex = m_idcList.GetNextItem(-1, LVNI_SELECTED);
	
	memset(m_Config->m_UserInfo.curFriend,0,32);
	if(nIndex >= 0)
	{
		BSTR strText=NULL;
		m_idcList.GetItemText(nIndex, 0, strText);
		//wcstombs(m_Config->m_UserInfo.curFriend, strText, wcslen(strText)+1 );
		DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,strText,-1,NULL,0,NULL,FALSE);
		WideCharToMultiByte (CP_OEMCP,NULL,strText,-1,m_Config->m_UserInfo.curFriend,dwNum,NULL,FALSE);
	}

	return 0L;
}

LRESULT CMainDlg::OnListClick(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
	//OnCateDetail(0, 0, 0, bHandled);
// 	int nIndex = m_idcList.GetNextItem(-1, LVNI_SELECTED);
// 	CString s;
// 	s.Format(_T("You choose index :%d"),nIndex);
// 	MessageBox(s,_T("test"));

	//CMediaListDlg dlg(&m_ContoSrv);
	//dlg.DoModal();
	ShowMediaList(NULL);


	return 0L;
}

void CMainDlg::ShowMediaList(TCHAR* userName)
{
	//get filename
	TCHAR filename[256] = {0};
	int nIndex = m_idcList.GetNextItem(-1, LVNI_SELECTED);

	if(nIndex < 0)
	{
		CString caption;
		CString msg;
		caption.LoadString(IDS_ERR_CAP);
		msg.LoadString(IDS_ERR_SELECTUSER);
		MessageBox(msg,  caption);
		return;
	}

	BSTR strText=NULL;
	m_idcList.GetItemText(nIndex, 0, strText);

	if(IsFileExist(U_TEMPMEDIALIST))
	{
		DeleteFile(U_TEMPMEDIALIST);
	}

	char tmp[MAX_PATH] = {0};
	//sprintf(tmp,"%S",strText);
	DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,strText,-1,NULL,0,NULL,FALSE);
	WideCharToMultiByte (CP_OEMCP,NULL,strText,-1,tmp,dwNum,NULL,FALSE);

	::SetCursor(::LoadCursor(NULL, IDC_WAIT));
	if( 200 != m_ContoSrv->GetMediaList(tmp))
	{
		if(IsFileExist(U_TEMPMEDIALIST))
		{
			DeleteFile(U_TEMPMEDIALIST);
		}
	}
	::SetCursor(NULL);

	CMediaListDlg dlg(m_ContoSrv,m_Config);
	dlg.DoModal();
}

int CMainDlg::LoadUsers()
{
	//get data from file
	m_UserArray.RemoveAll();
	FILE *fp;
	fp = fopen(A_TEMPUSERLIST, "r+b");
	if(fp) 
	{
		char buf[MAX_PATH] = {0};
		TCHAR wBuf[MAX_PATH] = {0};
		while (fgets(buf,MAX_PATH,fp))
		{
			//swprintf(wBuf,L"%S",buf);
			MultiByteToWideChar(CP_ACP, 0, buf, -1, wBuf, MAX_PATH);
			if(_tcslen(wBuf)>2) 
			{
				int len = _tcslen(wBuf);
				if( (wBuf[len-2] == '\r') && (wBuf[len-1] == '\n')) //'\r\n'
				{
					len -=2;
				}
				
				TCHAR tmp[MAX_PATH] = {0};
				_tcsncpy(tmp,wBuf,len);
				m_UserArray.Add(*(TPath*)tmp);
			}
		}
		fclose(fp);
	}


	//update listview
	m_idcList.DeleteAllItems();
	int nIndex=0;
	for(int i=0;i<m_UserArray.GetSize();i++)
	{
		int j = _tcslen(m_UserArray[i].path);
		m_idcList.InsertItem(nIndex, m_UserArray[i].path, 0);
		nIndex++;
	}

	return nIndex;
}

LRESULT CMainDlg::OnVCR(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	memset(m_vcrName,0,MAX_PATH);
	
	char vcrName[256] = {0};
	SYSTEMTIME st;
	GetLocalTime(&st);
	sprintf(vcrName,"%04d%02d%02d_%02d%02d%02d.%s", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond,A_MEDIAEXT);
	sprintf(m_vcrName,"%s%s",A_TEMPFILEDIR,vcrName);

	StartCamera(m_hWnd,A_TEMPFILEDIR,vcrName,CAMERACAPTURE_MODE_VIDEOWITHAUDIO);

	TCHAR buf[256] = {0};
	wsprintf(buf,L"%S",m_vcrName);
	if(IsFileExist(buf))
	{
		CString caption;
		CString msg;
		caption.LoadString(IDS_QUERY_CAP);
		msg.LoadString(IDS_QUERY_UPLOAD);
		if(IDYES == ::MessageBox(m_hWnd ,msg,  caption, MB_YESNO | MB_SETFOREGROUND))
		{
			//TODO: UPLOAD
			::SetCursor(::LoadCursor(NULL, IDC_WAIT));
			bool bRetVal = m_ContoSrv->UploadMediaFile(m_vcrName,m_Config->m_UserInfo.userName,vcrName);
			::SetCursor(NULL);

			if(bRetVal)
				msg.LoadString(IDS_UPDATA_OK);
			else
				msg.LoadString(IDS_UPDATA_ERR);

			CString tmpMsg(vcrName);
			tmpMsg += msg;

			//tmpMsg.Format("%s%S",vcrName,msg);
			MessageBox(tmpMsg,caption);
		}
	}

	return 0L;
}

LRESULT CMainDlg::OnUpdataUser(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	//PROCESS_INFORMATION *pProcInfo = NULL;
	//::CreateProcess(L"\\windows\\player.exe", L"\\test.3gp", NULL, NULL, FALSE, 0, NULL, NULL, NULL, pProcInfo);
	int oFileSize = GetFileSize(U_TEMPUSERLIST);
	int retVal = 0;
	::SetCursor(::LoadCursor(NULL, IDC_WAIT));
	retVal = m_ContoSrv->GetUserList();
	::SetCursor(NULL);

	if(retVal != 200)
	{
		CString caption;
		CString msg;
		caption.LoadString(IDS_ERR_CAP);
		msg.LoadString(IDS_ERR_LOGIN);
		MessageBox(msg,  caption);
		return 0L;
	}
	
	int nFileSize = GetFileSize(U_TEMPUSERLIST);
	if(oFileSize != nFileSize)
	{
		LoadUsers();
	}

	return 0L;
}

LRESULT CMainDlg::OnViewMedia(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	//CMediaListDlg dlg;
	//dlg.DoModal();

	//m_ContoSrv->UploadFile("\\test.3gp","Mark");
	//STLOG_WRITE("http://59.108.23.204/web/mshare/test.txt");
	//m_ContoSrv->DownloadFileByUrl(L"http://59.108.23.204/web/mshare/test.txt","\\20090718.txt");
	ShowMediaList(NULL);
	return 0L;
}

LRESULT CMainDlg::OnLogin(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	m_bLogined = false;

	m_idcList.DeleteAllItems();

	wchar_t		buf[32] = {0};
	GetDlgItemText( IDC_NAME, buf, 32 );
	//wcstombs(m_Config->m_UserInfo.userName, buf, wcslen(buf)+1 );
	DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,buf,-1,NULL,0,NULL,FALSE);
	WideCharToMultiByte (CP_OEMCP,NULL,buf,-1,m_Config->m_UserInfo.userName,dwNum,NULL,FALSE);

	GetDlgItemText( IDC_PSW, buf, 32 );
	//wcstombs(m_Config->m_UserInfo.userPsw, buf, wcslen(buf)+1 );
	dwNum = WideCharToMultiByte(CP_OEMCP,NULL,buf,-1,NULL,0,NULL,FALSE);
	WideCharToMultiByte (CP_OEMCP,NULL,buf,-1,m_Config->m_UserInfo.userPsw,dwNum,NULL,FALSE);

	CString caption;
	CString msg;
	caption.LoadString(IDS_ERR_CAP);

	if(strlen(m_Config->m_UserInfo.userName) <= 0)
	{
		msg.LoadString(IDS_NOTINPUT_USERNAME);
		MessageBox(msg,  caption);	
	}

	::SetCursor(::LoadCursor(NULL, IDC_WAIT));

	DeleteFile(U_TEMPUSERLIST);
	
	int ret = m_ContoSrv->GetUserList(m_Config->m_UserInfo.userName);// && IsFileExist(U_TEMPUSERLIST);
	if(200 == ret)
	{
		m_bLogined = true;
		LoadUsers();
		::SetCursor(NULL);
	}
	else
	{
		::SetCursor(NULL);
		msg.LoadString(IDS_ERR_LOGIN);
		MessageBox(msg,  caption);	
	}

	return 0L;
}

VOID CMainDlg::StartCamera(HWND hwndDlg,char* path, char* name, CAMERACAPTURE_MODE mode)
{
	HRESULT         hr;
	HRESULT         hReturn;
	SHCAMERACAPTURE shcc;

	TCHAR           szInitialDir[256] = { 0 };
	TCHAR           szDefaultFileName[128] = { 0 };

	wsprintf(szInitialDir,L"%S",path);
	wsprintf(szDefaultFileName,L"%S",name);

	// Specify the arguments of SHCAMERACAPTURE
	ZeroMemory(&shcc, sizeof(shcc));
	shcc.cbSize             = sizeof(shcc);
	shcc.hwndOwner          = hwndDlg;
	shcc.pszInitialDir      = szInitialDir;
	shcc.pszDefaultFileName = szDefaultFileName;
	//shcc.nResolutionWidth	= 480;
	//shcc.nResolutionHeight  = 640;
	shcc.StillQuality       = CAMERACAPTURE_STILLQUALITY_DEFAULT;
	shcc.VideoTypes         = CAMERACAPTURE_VIDEOTYPE_ALL;
	shcc.Mode               = mode;

	// Call SHCameraCapture() function
	hReturn = SHCameraCapture(&shcc);

	// Check the return codes of the SHCameraCapture() function
	switch (hReturn)
	{
	case S_OK:
		// The method completed successfully.
		
		break;
	case S_FALSE:
		// The user canceled the Camera Capture dialog box.
		break;
	case E_INVALIDARG:
		// An invalid argument was specified.
		break;
	case E_OUTOFMEMORY:
		// There is not enough memory to save the image or video.
		break;
	default:
		// An unknown error occurred.
		break;
	}

Error:
	return;
}

